<?php
/**
 * Created by PhpStorm.
 * User: ownfi
 * Date: 2017-03-13
 * Time: 19:45
 */

namespace App\Services\Impl;

use App\Common\Constant\CacheKey;
use App\Models\Province;
use App\Services\ISystemService;
use Cache;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Log;

class SystemServiceImpl implements ISystemService
{

    public function genOrderNumber()
    {
        return 'LB'.date('ymdHis').random(6,'UCNUMBER');
    }

    public function genTradeNumber()
    {
        return date('ymdHis').sprintf('%u',crc32(microtime(true))).random(8,'UCNUMBER');
    }

    public function genInsideOrderNumber()
    {
        return 'LBINSIDE'.date('ymdHis').random(6,'UCNUMBER');
    }

    public function alert($message)
    {
        session()->flash('alert',$message);
    }

    public function requestUrl($url, $data = null, $method = 'GET')
    {
        Log::info("System request method: {$method}, url: {$url}",(array)$data);
        try {
            $client = new Client();
            $response = $client->request($method, $url, [
                'query' => $data ? (array)$data : []
            ]);
            return $response->getStatusCode() == 200 ? $response->getBody() : false;
        } catch (RequestException $e) {
            throw $e;
        }
    }

    public function requestApi($url, $data = null, $method = 'GET')
    {
        Log::info("System request api method: {$method}, url: {$url}",(array)$data);
        try {
            $data = (array)$data ? : [];
            $data['sign'] = uc_authcode(config('app.key'),'ENCODE',300,config('services.ApiAppKey'));

            $client = new Client();
            $response = $client->request($method, $url, [
                'query' => $data
            ]);
            if ($response->getStatusCode() != 200){
                return false;
            }
            $json = json_decode($response->getBody(),true);
            if (!is_array($json)){
                return false;
            }
            if ($json['code'] != 200){
                return false;
            }
            return $json;
        } catch (RequestException $e) {
            throw $e;
        }
    }

}